package com.yc.hwc.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.yc.hwc.bean.PageImpl;
import com.yc.hwc.bean.User;
import com.yc.hwc.dao.SqlDao;

@RestController
public class QueryDo {

	@Resource
	private SqlDao dao;

	@RequestMapping("top/{id}")
	public PageImpl<Map<String, Object>> top(@PathVariable String id, 
			String group, String condition, int tops,
			@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "5") int size,
			HttpServletRequest req, HttpSession session) {
		Map<String,Object> param = asParamMap(req.getParameterMap(), session);
		param.remove("group");
		param.remove("condition");
		param.remove("tops");
		param.remove("page");
		param.remove("size");
		return dao.top(id, group, condition, tops,page,size, param);
	}
	
	@RequestMapping("list/{id}")
	public List<Map<String, Object>> list1(@PathVariable String id, HttpServletRequest req, HttpSession session) {
		return dao.list(id, asParamMap(req.getParameterMap(), session));
	}

	@RequestMapping("one/{id}")
	public Map<String, Object> one1(@PathVariable String id, HttpServletRequest req, HttpSession session) {
		return dao.one(id, asParamMap(req.getParameterMap(), session));
	}

	@RequestMapping("val/{id}")
	public Object val1(@PathVariable String id, HttpServletRequest req, HttpSession session) {
		return dao.val(id, asParamMap(req.getParameterMap(), session));
	}

	private Map<String, Object> asParamMap(Map<String, String[]> parameterMap, HttpSession session) {
		Map<String, Object> ret = new HashMap<String, Object>();
		for (Entry<String, String[]> e : parameterMap.entrySet()) {
			if (e.getValue().length > 1 || e.getKey().endsWith("[]")) {
				String name = e.getKey().endsWith("[]") ? e.getKey().substring(0, e.getKey().length() - 2) : e.getKey();
				ret.put(name, e.getValue());
			} else {
				ret.put(e.getKey(), e.getValue()[0]);
			}
		}
		User user = (User) session.getAttribute("loginedUser");
		if(user!=null) {
			if(ret.containsKey("mycls")) { ret.put("mycls", user.getClsSn());}
			if(ret.containsKey("myid")) { ret.put("myid", user.getId());}
		}
		return ret;
	}

}
